<template>
  <a-spin :spinning="confirmLoading">
    <a-form ref="formRef" class="antd-modal-form" :labelCol="labelCol" :wrapperCol="wrapperCol">
      <a-row>
        <a-col :span="13">
          <a-form-item label="资质名称" v-bind="validateInfos.flaName">
            <a-input v-model:value="formData.flaName" placeholder="必填" style="width: 350px" :disabled="disabled"></a-input>
          </a-form-item>
          <a-form-item label="考核内容" v-bind="validateInfos.exam">
            <div style="margin-bottom: 20px">
              <span v-for="item in message" :key="item.id" class="tag-container"
                >{{ item.name }}
                <span class="close-btn" @click="removeTag(item.id)">x</span>
              </span>
            </div>
          </a-form-item>
          <div style="margin-left: 105px; margin-top: -26px; margin-bottom: 20px">
            <a-button
              style="width: 128px; height: 28px; font-size: 10px"
              type="primary"
              preIcon="ant-design:plus-outlined"
              @click="selectAddExam"
              :disabled="disabled"
              >添加考核内容</a-button
            >
          </div>
          <a-form-item label="资质权限" v-bind="validateInfos.content">
            <div>
              <div v-for="item in list" :key="item.id" class="tag-container-item">
                <span class="tag-container-item-text">{{ item.title }}</span>
                <div class="tag-container-tag">
                  <span v-if="item.children && item.children.length > 0" v-for="child in item.children" :key="child.id" class="tag-container">{{
                    child.title
                  }}</span>
                </div>
              </div>
            </div>
          </a-form-item>
          <div style="margin-left: 105px; margin-top: -30px">
            <a-button
              style="width: 108px; height: 28px; font-size: 10px"
              v-if="dis"
              type="primary"
              preIcon="ant-design:plus-outlined"
              @click="checkItems"
              :disabled="disabled"
              >添加资质</a-button
            >
          </div>
        </a-col>

        <!--项目树-->
        <a-col :span="10">
          <div class="tree-wrapper">
            <div class="tree-box">
              <h2 style="margin-left: 10px">资质选择</h2>
            </div>
            <div class="tree-container">
              <a-tree
                v-model:expandedKeys="expandedKeys"
                v-model:selectedKeys="selectedKeys"
                v-model:checkedKeys="checkedKeys"
                checkable
                :tree-data="treeData"
                autoExpandParent="true"
                :disabled="dis"
              >
                <template #title="{ title, key }">
                  <span v-if="key === '0-0-1-0'" style="color: #1890ff">{{ title }}</span>
                  <template v-else>{{ title }}</template>
                </template>
              </a-tree>
            </div>
            <a-button v-if="!dis" style="width: 72px; height: 28px; margin-left: 100px; margin-top: 30px; margin-bottom: 20px" @click="handleReset"
              >重置</a-button
            >
            <a-button v-if="!dis" style="width: 72px; height: 28px; margin-left: 30px" type="primary" @click="handleSubmit">确认</a-button>
          </div>
        </a-col>
      </a-row>
    </a-form>
  </a-spin>
  <ExamSelectModal rowKey="id" @register="registerSelExamModal" @getSelectResult="onSelectChemicalOk" style="height: 40px; overflow: auto" />
</template>

<script lang="ts" setup>
  import { ref, reactive, defineExpose, nextTick, defineProps, computed } from 'vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { getValueType } from '/@/utils';
  import { saveOrUpdate, itemsTree } from '../LabFlair.api';
  import { Form } from 'ant-design-vue';
  import { useModal } from '/@/components/Modal/index';
  import ExamSelectModal from '../components/ExamSelectModal.vue';

  const props = defineProps({
    formDisabled: { type: Boolean, default: false },
    formData: { type: Object, default: () => {} },
    formBpm: { type: Boolean, default: true },
  });
  const formRef = ref();
  const useForm = Form.useForm;
  const emit = defineEmits(['register', 'ok', 'select', 'rootTreeData']);
  const formData = reactive<Record<string, any>>({
    id: '',
    flaName: '',
    exam: '',
    setUp: '',
    content: '',
  });
  const { createMessage } = useMessage();
  const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 5 } });
  const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 16 } });
  const confirmLoading = ref<boolean>(false);
  //表单验证
  const validatorRules = {
    flaName: [{ validator: validateFlaName, trigger: 'blur' }],
  };
  function validateFlaName(rule, value, callback) {
    if (value) {
      // 已存在值，校验通过
      callback();
    } else {
      // 为空，返回错误消息
      callback(new Error('请输入名称!'));
    }
  }
  const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: true });

  // 表单禁用
  const disabled = computed(() => {
    if (props.formBpm === true) {
      if (props.formData.disabled === false) {
        return false;
      } else {
        return true;
      }
    }
    return props.formDisabled;
  });
  const [registerSelExamModal, selExamModal] = useModal();
  // 选择添加考试
  function selectAddExam() {
    selExamModal.openModal();
  }

  const message = ref();
  async function onSelectChemicalOk(options, userIdList, selectRows) {
    //选中的考试
    message.value = selectRows.value; //后端查出的考试信息
  }
  async function removeTag(id) {
    message.value = message.value.filter((item) => item.id !== id);
  }

  const dis = ref(true);
  function handleSubmit() {
    let filteredKeys = [];
    console.log('checkedKeys.value', checkedKeys.value);
    if (checkedKeys.value !== null) {
      // 获取选中的树节点数据
      filteredKeys = checkedKeys.value.filter((key) => key.length >= 5);
    }

    console.log('filteredKeys', filteredKeys);
    // 通过遍历treeData，在节点中查找选中的key所对应的值
    const selectedValues = findNodeByKey(treeData.value, filteredKeys);
    console.log('selectedValues', selectedValues);
    list.value = selectedValues;
    // 将 disabled 的值改为 true
    dis.value = true;
  }
  function handleReset() {
    // 重置树数据和状态
    checkedKeys.value = [];
    list.value = [];
  }

  function checkItems() {
    dis.value = false;
  }
  /**树 */
  const treeData = ref([]);
  const expandedKeys = ref<string[]>(['0-0-0', '0-0-1']);
  const selectedKeys = ref<string[]>(['0-0-0', '0-0-1']);
  const checkedKeys = ref<string[]>(['0-0-0', '0-0-1']);

 

  function selectItems() {
    itemsTree().then((res) => {
      treeData.value = convertToTree(res);
      handleSubmit();
    });
  }
  function convertToTree(data) {
    // 创建一个映射表，用于通过id查找对应的节点
    const nodeMap = new Map();
    // 遍历数据，将每个节点添加到映射表中
    data.forEach((node) => {
      // 将节点转换为树节点格式，并存储在映射表中
      nodeMap.set(node.id, {
        id: node.id,
        title: node.name, // 假设节点有一个title属性作为显示文本
        children: [],
      });
    });
    // 构建树结构
    const tree = [];
    data.forEach((node) => {
      const treeNode: any = nodeMap.get(node.id);
      const parentId = node.pid;

      // 如果节点存在父节点，则将自身添加到父节点的children数组中
      if (parentId) {
        const parentNode = nodeMap.get(parentId);
        if (parentNode) {
          parentNode.children.push(treeNode);
        }
      } else {
        // 没有父节点的节点视为顶级节点
        tree.push(treeNode);
      }
    });
    return tree;
  }
  // 在树结构中通过key查找节点
  const list = ref();

  function findNodeByKey(nodes: { key: string; children: any[] }[], filteredKeys: string[]): any[] {
    const resultList = []; // 结果列表
    const res = JSON.parse(JSON.stringify(nodes)); // 使用深拷贝创建副本
    let i = 0;
    filteredKeys.forEach((key) => {
      const keys = key.split('-'); // 将 key 字符串按照 "-" 分割成数组
      const middleKey = keys[1]; // 获取中间位置的值
      const lastKey = keys[2];
      const idList = resultList.map((obj) => obj.id);

      if (!idList.includes(nodes[middleKey].id)) {
        const mid = nodes[middleKey].children[lastKey];
        res[middleKey].children = [];
        res[middleKey].children.push(mid);
        resultList.push(res[middleKey]); // 将 nodes[middleKey] 添加到 resultList
      } else {
        for (let i = 0; i < resultList.length; i++) {
          if (resultList[i].id === nodes[middleKey].id) {
            // 对找到的对象进行修改
            // 这里可以根据需要修改对象的属性
            resultList[i].children.push(nodes[middleKey].children[lastKey]);
            break; // 找到后结束循环
          }
        }
      }
    });

    return resultList;
  }

  /**
   * 新增
   */
  function add() {
    // edit({});
    message.value = [];
    checkedKeys.value = [];
    selectedKeys.value = [];
    expandedKeys.value = [];
    selectItems();
    nextTick(() => {
      resetFields();
      //赋值
      Object.assign(formData);
    });
  }

  /**
   * 编辑
   */
  async function edit(record) {
    checkedKeys.value = [];
    selectedKeys.value = [];
    expandedKeys.value = [];
    message.value = record.myExam;
    checkedKeys.value = record.myNode;
    selectItems();
    nextTick(() => {
      resetFields();
      //赋值
      Object.assign(formData, record);
    });
  }

  /**
   * 提交数据
   */
  async function submitForm() {
    // 触发表单验证
    await validate();
    confirmLoading.value = true;
    const isUpdate = ref<boolean>(false);
    //时间格式化
    let model = formData;
    if (model.id) {
      isUpdate.value = true;
    }
    //循环数据
    for (let data in model) {
      //如果该数据是数组并且是字符串类型
      if (model[data] instanceof Array) {
        let valueType = getValueType(formRef.value.getProps, data);
        //如果是字符串类型的需要变成以逗号分割的字符串
        if (valueType === 'string') {
          model[data] = model[data].join(',');
        }
      }
    }

    if (message.value !== undefined) {
      // value 属性存在的逻辑处理
      const text = JSON.parse(JSON.stringify(message.value));
      model.myExam = text;
    } else {
      model.myExam = JSON.parse(JSON.stringify([]));
    }

    if (list.value !== undefined) {
      const idList = [];
      list.value.forEach((obj) => {
        const children = obj.children;
        // 然后在这里对 children 进行你的操作
        children.forEach((child) => {
          // const id = child.id;
          idList.push(child);
        });
      });
      const ids = JSON.parse(JSON.stringify(idList));
      model.myContent = ids;

      model.myNode = JSON.parse(JSON.stringify(checkedKeys.value));
    }
    await saveOrUpdate(model, isUpdate.value)
      .then((res) => {
        if (res.success) {
          createMessage.success(res.message);
          emit('ok');
        } else {
          createMessage.warning(res.message);
        }
      })
      .finally(() => {
        confirmLoading.value = false;
      });
  }

  defineExpose({
    add,
    edit,
    submitForm,
  });
</script>

<style lang="less" scoped>
  .antd-modal-form {
    min-height: 500px !important;
    overflow-y: auto;
    padding: 24px 24px 24px 24px;
  }

  .tag-container {
    // width: 195px;
    height: 28px;
    background: #d9edeb;
    border: 1px solid #ccc;
    border-radius: 4px 4px 4px 4px;
    opacity: 1;
    margin-right: 10px;
    margin-top: 8px;
    padding: 2px 5px;
  }

  .tag-container-item {
    margin-top: 5px;
    margin-bottom: 20px;
  }
  .tag-container-tag {
    display: flex;
    flex-wrap: wrap;
  }
  .close-btn {
    font-weight: bold;
    cursor: pointer;
    margin-left: 5px;
    margin-top: -2px;
  }

  .tree-container {
    height: 300px;
    /* 设置容器高度为300px */
    overflow-y: auto;
    /* 设置垂直方向上的溢出内容显示滚动条 */
  }

  .list-separator {
    margin-top: 50px;
  }

  .tree-wrapper {
    border: 1px solid #ccc;
    /* 设置边框样式 */
  }

  .tree-box {
    background-color: #009688;
    /* 设置背景颜色 */
  }
</style>
